import hashlib
import os
import django
import datetime
from django.utils import timezone
import sys

sys.path.append(os.path.dirname(__file__) + os.sep + "../")  # 添加上级目录到环境变量
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
                      "teachzero.settings")  # 处理django环境变量
django.setup()

TYPE_LIST = [".pdf", ".html"]
WHITE_LIST = ["拓展练习",]
BLACK_LIST = ["答案", "重点知识", "作业", "课堂练习题", "大纲", "练习", "训练", "案例","循环结构大综合" ,"反馈","课堂记录"]


class My_db(object):
    def __init__(self):
        """
        加载数据库
        """
        # print(settings.PATH)
        # self.datas = []

    def load_data(self, func_type):
        print("load_data")
        """
        加载课程或者试题
        """
        from teachzero import settings

        PATH = settings.PATH[func_type]
        print("PATH:",PATH)
        datas = []
        for path, dirnames, filenames in os.walk(PATH):
            for file in filenames:
                file_type = os.path.splitext(file)[1]
                flag = 1
                if not file_type in TYPE_LIST:
                    flag = 0
                for i in BLACK_LIST:
                    if i in file:
                        flag = 0
                        break
                for i in WHITE_LIST:
                    if i in file:
                        flag = 1
                        break
                if flag:
                    real_path = os.path.join(path, file)
                    paths = os.path.normpath(real_path)
                    paths = paths.split(os.sep)
                    func_type_index = paths.index(func_type)
                    item_type = paths[func_type_index + 1]  # 类型名称
                    lv = paths[func_type_index + 2]  # 级别名称
                    mtime = os.path.getmtime(real_path)
                    mtime = datetime.datetime.fromtimestamp(
                        mtime)  # 转换成datetime
                    mtime = timezone.make_aware(
                        mtime, timezone.get_current_timezone())
                    number = ""
                    for i in paths[func_type_index + 3]:  # 遍历课程名称
                        if i in "0123456789":
                            number += i
                        else:
                            break
                    try:
                        number = int(number)
                    except:
                        number = 0
                    name = os.path.splitext(file)[0]
                    url = os.path.join("/static", *paths[func_type_index:])
                    item_dict = {
                        "item_type": item_type,
                        "lv": lv,
                        "number": number,
                        "name": name,
                        "path": real_path,
                        "md5": hashlib.md5((real_path).encode("utf-8")).hexdigest(),
                        "url": url,
                        "func_type": func_type,
                        "modified_time": mtime,
                        "show": True,
                    }
                    datas.append(item_dict)
        datas = sorted(
            datas, key=lambda x: (
                x["item_type"], x["lv"], x["number"], x["name"])
        )
        return datas

    def update_data(self):
        print("update_data")
        """
        重建课程和训练数据库
        """
        from teach.models import Item
        from teachzero import settings

        types = ["lesson", "training"]
        # Item.objects.all().delete()
        for item in Item.objects.all():
            flag = 0
            print("item:",item)
            if os.path.isfile(item.path):# 如果讲义存在
                for func_type in types:# 查找是不是某种类型
                    if item.path.startswith(settings.PATH[func_type]):
                        flag = 1
                        break
            if flag == 0:
                try:
                    item.delete()
                    print(f"【{item.name}】删除成功...")
                except:
                    print(f"【{item.name}】删除失败...")
        for func_type in types:
            datas = self.load_data(func_type)
            print("datas:",datas)
            for data in datas:
                item = Item.objects.filter(
                    path=data["path"],
                )
                if item:
                    item = item[0]
                    item.number = data["number"]
                    item.url = data["url"]
                    item.path = data["path"]
                    item.md5 = data["md5"]
                    item.func_type = data["func_type"]
                    item.item_type = data["item_type"]
                    item.lv = data["lv"]
                    item.modified_time = data["modified_time"]
                    item.save()
                else:
                    item = Item(
                        number=data["number"],
                        name=data["name"],
                        url=data["url"],
                        path=data["path"],
                        md5=data["md5"],
                        func_type=data["func_type"],
                        item_type=data["item_type"],
                        lv=data["lv"],
                        modified_time=data["modified_time"],
                    )
                    item.save()
                print(item.id, item.name)

    def get_data(self, md5):
        """
        根据md5获取真实地址
        """
        from teach.models import Item

        item = Item.objects.filter(md5=md5)
        if item:
            return item
        else:
            print("未查询到")


if __name__ == "__main__":
    my_db = My_db()
    my_db.update_data()
    # print(my_db.get_data('8c560a47a889d5d032187d0ae483b3d1'))
